<?php

namespace App\traits;

use Illuminate\Support\Facades\DB;

/**
 * mysql insert ignore,replace 插入语句.
 */
trait InsertReplaceable
{
    public static function insertReplace(array $attributes = [])
    {
        return static::executeQuery('replace', $attributes);
    }

    public static function insertIgnore(array $attributes = [])
    {
        return static::executeQuery('insert ignore', $attributes);
    }

    protected static function executeQuery($command, array $attributes)
    {
        $prefix = DB::connection()->getTablePrefix();
        if (!count($attributes)) {
            return true;
        }
        $model = new static();
        if (false === $model->fireModelEvent('saving')) {
            return false;
        }
        $attributes = collect($attributes);
        $first = $attributes->first();
        if (!is_array($first)) {
            $attributes = collect([
                $attributes->toArray(),
            ]);
        }
        $keys = collect($attributes->first())->keys()->transform(function ($key) {
            return '`'.$key.'`';
        });
        $bindings = [];
        $query = $command.' into '.$prefix.$model->getTable().' ('.$keys->implode(',').') values ';
        $inserts = [];
        foreach ($attributes as $data) {
            $qs = [];
            foreach ($data as $value) {
                $qs[] = '?';
                $bindings[] = $value;
            }
            $inserts[] = '('.implode(',', $qs).')';
        }
        $query .= implode(',', $inserts);
        DB::connection($model->getConnectionName())->insert($query, $bindings);
        $model->fireModelEvent('saved', false);
    }
}
